import { uploadChunks } from "@/api/backend";
import axios from "axios";

export async function queueUpload(
  tasks: any[],
  max = 5,
  onProgress: any,
  onChunkProgress: any,
  signal: any
) {
  return new Promise((resolve, reject) => {
    const results: any[] = [];
    if (tasks.length === 0) {
      resolve(results);
      return;
    }

    let curTask = 0;
    let count = 0;
    const progress: number[] = [];

    function run() {
      while (count < max && curTask < tasks.length) {
        const task = tasks[curTask];
        uploadChunks(task, onUploadProgress(curTask), signal)
          .then((res) => {
            count--;
            if (curTask === tasks.length && count === 0) {
              resolve(results);
            } else {
              results.push(res);
              run();
            }
          })
          .catch((e) => {
            if (axios.isCancel(e)) {
              reject("已取消上传");
            } else {
              reject(e);
            }
          });
        count++;
        curTask++;
      }
    }

    function onUploadProgress(curTask: number) {
      return (pe: any) => {
        progress[curTask] = pe.loaded / pe.total;
        onChunkProgress(progress);
        onProgress(progress.reduce((a, c) => a + c) / tasks.length);
      };
    }

    run();
  });
}
